#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/mman.h>

#define BUFFER_SIZE 5

typedef struct {
    int buffer[BUFFER_SIZE];
    int in;
    int out;
    sem_t empty;
    sem_t full;
    sem_t mutex;
} shared_data_t;

int main() {
    // 创建共享内存
    int shm_fd = shm_open("/my_shm", O_CREAT | O_RDWR, 0666);
    ftruncate(shm_fd, sizeof(shared_data_t));
    shared_data_t *shared_data = (shared_data_t *)mmap(NULL, sizeof(shared_data_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);

    // 初始化信号量
    sem_init(&(shared_data->empty), 1, BUFFER_SIZE);
    sem_init(&(shared_data->full), 1, 0);
    sem_init(&(shared_data->mutex), 1, 1);

    int data = 1;
    while (1) {
        sem_wait(&(shared_data->empty)); // 等待缓冲区非满
        sem_wait(&(shared_data->mutex)); // 加锁

        shared_data->buffer[shared_data->in] = data;
        printf("Produced: %d\n", data);
        data++;
        shared_data->in = (shared_data->in + 1) % BUFFER_SIZE;

        sem_post(&(shared_data->mutex)); // 解锁
        sem_post(&(shared_data->full));  // 增加缓冲区内数据数量

        sleep(1); // 生产数据后等待一段时间
    }

    munmap(shared_data, sizeof(shared_data_t));
    shm_unlink("/my_shm");
    sem_destroy(&(shared_data->empty));
    sem_destroy(&(shared_data->full));
    sem_destroy(&(shared_data->mutex));

    return 0;
}
